<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .dialog {
        position: fixed;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.3);
        justify-content: center;
        align-items: center;
        display: none;
      }

      .dialog form {
        width: 600px;
        background: white;
        padding: 20px;
      }

      .pagenation {
        padding: 0;
        margin: 0;
        display: flex;
      }
      .pagenation li {
        width: 30px;
        height: 30px;
        border: solid black;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
      }
      .pagenation li:hover {
        background-color: blue;
        color: white;
      }

      .pagenation li.active {
        background-color: blue;
        color: white;
      }
    </style>
  </head>
  <body>
    <button data-action="add">添加</button>
    <div class="dialog" id="addDialog">
      <form name="addForm">
        <fieldset>
          <legend>添加</legend>
          <p>姓名 <input type="text" name="name" /></p>
          <p>年龄 <input type="text" name="age" /></p>
          <p>
            性别 <input checked type="radio" name="gender" value="1" /> 男
            <input type="radio" name="gender" value="2" /> 女
          </p>
          <p>
            <button type="button" data-action="addSave">保存</button>
            <button type="button" data-action="closeAddDialog">取消</button>
          </p>
        </fieldset>
      </form>
    </div>

    <div>
      <input id="searchValue" type="text" /><button data-action="search">
        搜索
      </button>
    </div>

    <div onchange="chaneThead()">
      <input type="checkbox" name="thead" value="id" checked />编号
      <input type="checkbox" name="thead" value="name" checked />姓名
      <input type="checkbox" name="thead" value="age" checked />年龄
      <input type="checkbox" name="thead" value="gender" />性别
    </div>

    <div class="dialog" id="editDialog">
      <form name="editForm">
        <fieldset>
          <legend>添加</legend>
          <input type="text" name="id" hidden />
          <p>姓名 <input type="text" name="name" /></p>
          <p>年龄 <input type="text" name="age" /></p>
          <p>
            性别 <input checked type="radio" name="gender" value="1" /> 男
            <input type="radio" name="gender" value="2" /> 女
          </p>
          <p>
            <button type="button" data-action="editSave">保存</button>
            <button type="button" data-action="closeEditDialog">取消</button>
          </p>
        </fieldset>
      </form>
    </div>
    <div id="content"></div>
    <div id="pagenation"></div>
    <script>
      renderTable(document.getElementById("content"));
      const methods = {
        search() {
          renderTable(document.getElementById("content"));
        },
        toPage() {
          const page = this.dataset.page;
          renderTable(document.getElementById("content"), page);
        },
        editSave() {
          const form = document.editForm;
          const xhr = new XMLHttpRequest();
          xhr.open("PATCH", `http://127.0.0.1:8081/users/${form.id.value}`);
          xhr.setRequestHeader("Content-Type", "application/json");
          xhr.onload = function () {
            editDialog.style.display = "none"; //关闭对话框
            renderTable(document.getElementById("content"));
          };
          xhr.send(
            JSON.stringify({
              name: form.name.value,
              age: form.age.value,
              gender: form.gender.value,
            })
          );
        },
        edit() {
          const form = document.editForm;
          editDialog.style.display = "flex";
          const id = this.dataset.id;
          // 根据ID获取数据
          const xhr = new XMLHttpRequest();
          xhr.open("GET", `http://127.0.0.1:8081/users/${id}`);
          xhr.responseType = "json";
          xhr.onload = function () {
            // 回填数据
            form.id.value = xhr.response.id;
            form.name.value = xhr.response.name;
            form.age.value = xhr.response.age;
            form.gender.value = xhr.response.gender;
          };
          xhr.send();
        },
        add() {
          addDialog.style.display = "flex";
        },
        del() {
          const id = this.dataset.id;
          if (confirm("确定删除吗？") === false) return;
          // 请求添加数据
          const xhr = new XMLHttpRequest();
          xhr.open("DELETE", `http://127.0.0.1:8081/users/${id}`);
          xhr.onload = function () {
            renderTable(document.getElementById("content"));
          };
          xhr.send();
        },
        addSave() {
          const form = document.addForm;
          // 获取表单数据
          const name = form.name.value;
          const age = form.age.value;
          const gender = form.gender.value;

          // 请求添加数据
          const xhr = new XMLHttpRequest();
          xhr.open("POST", "http://127.0.0.1:8081/users");
          xhr.setRequestHeader("Content-Type", "application/json");
          xhr.onload = function () {
            // 添加成功
            addDialog.style.display = "none"; //关闭对话框
            renderTable(document.getElementById("content"));
          };
          xhr.send(JSON.stringify({ name, gender, age }));
        },
        closeAddDialog() {
          addDialog.style.display = "none";
        },
        closeEditDialog() {
          editDialog.style.display = "none";
        },
      };

      function chaneThead() {
        renderTable(document.getElementById("content"));
      }
      //-----
      function renderTable(container, page = 1) {
        const html = String.raw;
        const xhr = new XMLHttpRequest();

        // 全文查询
        let url = "";
        let keyword = searchValue.value;
        if (keyword) {
          url = `http://127.0.0.1:8081/users?_page=${page}&_limit=2&q=${keyword}`;
        } else {
          url = `http://127.0.0.1:8081/users?_page=${page}&_limit=2`;
        }
        xhr.open("GET", url);
        xhr.responseType = "json";
        xhr.onload = function () {
          const total = xhr.getResponseHeader("X-Total-Count");
          renderPagenation(
            document.getElementById("pagenation"),
            total,
            2,
            page
          );

          //动态表头
          const allowThead = [
            ...document.querySelectorAll('[name="thead"]:checked'),
          ].map((el) => el.value);
          container.innerHTML = html`
            <table border="1">
              <thead>
                <tr>
                  ${allowThead.includes("id") ? "<th>编号</th>" : ""}
                  ${allowThead.includes("name") ? "<th>姓名</th>" : ""}
                  ${allowThead.includes("age") ? "<th>年龄</th>" : ""}
                  ${allowThead.includes("gender") ? "<th>性别</th>" : ""}
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                ${xhr.response
                  .map(
                    (el) => html`
                      <tr>
                        ${allowThead.includes("id") ? `<td>${el.id}</td>` : ""}
                        ${allowThead.includes("name")
                          ? `<td>${el.name}</td>`
                          : ""}
                        ${allowThead.includes("age")
                          ? `<td>${el.age}</td>`
                          : ""}
                        ${allowThead.includes("gender")
                          ? `<td>${+el.gender === 1 ? "男" : "女"}</td>`
                          : ""}
                        <td>
                          <button data-action="del" data-id="${el.id}">
                            删除
                          </button>

                          <button data-action="edit" data-id="${el.id}">
                            编辑
                          </button>
                        </td>
                      </tr>
                    `
                  )
                  .join("")}
              </tbody>
            </table>
          `;
        };
        xhr.send();
      }

      function renderPagenation(container, total, limit, page = 1) {
        const html = String.raw;
        const pages = Math.ceil(total / limit);
        const pagesArr = Array.from({ length: pages }, (v, i) => i + 1);
        container.innerHTML = html` <ul class="pagenation">
          ${page > 1
            ? html`<li data-page="${+page - 1}" data-action="toPage">←</li>`
            : ""}
          ${pagesArr
            .map(
              (el) =>
                html`<li
                  class="${+page === el ? "active" : ""}"
                  data-page="${el}"
                  data-action="toPage"
                >
                  ${el}
                </li>`
            )
            .join("")}
          ${page < pages
            ? html`<li data-page="${+page + 1}" data-action="toPage">→</li>`
            : ""}
        </ul>`;
      }
      document.addEventListener("click", (e) => {
        const target = e.target;
        const action = target.dataset.action;
        if (action === undefined || methods[action] === undefined) return;
        methods[action].call(target);
      });
    </script>
  </body>
</html>
